package com.mrjoew.weekend.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author Christopher Jones
 * @ClassName BaseController
 * @explain
 * @date 2020/6/21 0021 22:38
 */
public class BaseController {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private MessageSource messageSource;

    /**
     * 获取对应国际化资源
     *
     * @param source
     * @return
     */
    public String translateI18N(String source) {
        return translateI18N(this.messageSource, source);
    }

    /**
     * 获取error国际化资源
     *
     * @param bindingResult
     * @return
     */
    public String translateI18N(BindingResult bindingResult) {
        return translateI18N(this.messageSource, bindingResult);
    }

    /**
     * 获取error国际化资源
     *
     * @param messageSource
     * @param bindingResult
     * @return
     */
    public static String translateI18N(MessageSource messageSource, BindingResult bindingResult) {
        StringBuffer sb = new StringBuffer();
        for (ObjectError objectError : bindingResult.getAllErrors()) {
            sb.append(translateI18N(messageSource, objectError.getDefaultMessage()) + ";\n");
        }
        return sb.toString();
    }

    /**
     * 获取对应国际化资源
     *
     * @param messageSource
     * @param source
     * @return
     */
    public static String translateI18N(MessageSource messageSource, String source) {
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(source, null, locale);
    }
}
